import * as React from 'react';

class Livere extends React.Component {
	timer = null;
	id = null;
	constructor(props) {
		super(props);
	}

	componentDidMount() {
		if (this.props.id !== this.id) {
			this.loadInstance();
			this.id = this.props.id;
		}
	}

	componentDidUpdate() {
		if (this.props.id !== this.id) {
			this.loadInstance();
			this.id = this.props.id;
		}
	}

	componentWillUnmount() {
		if (this.timer !== null) {
			clearTimeout(this.timer);
			this.timer = null;
			this.id = null;
		}
	}

	loadInstance() {
		if (!window) {
			return;
		}
		if (window.document.getElementById('livere-js') === null) {
			const script = window.document.createElement('script');
			script.async = true;
			script.src = "https://cdn-city.livere.com/js/embed.dist.js";
			script.id = 'livere-js';
			script.onload = () => {
				this.timer = setTimeout(() => {
					clearTimeout(this.timer);
					this.timer = null;
				}, 300);
			};
			window.document.body.appendChild(script);
			return;
		}
		if (window.LivereTower && this.timer === null) {
			this.timer = setTimeout(() => {
				try {
					window.LivereTower.reload();
				} catch (e) {
					window.LivereTower.init();
				}
				clearTimeout(this.timer);
				this.timer = null;
			}, 300);
		}
	}

	render() {
		return (
			<div id="lv-container" data-id="city" data-uid={this.props.uid}></div>
		);
	}
}

export default Livere;